<template>
  <div>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoadData"
    >
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
      </template>
      <template slot="menu" slot-scope="{ row, index }">
        <el-button type="text" size="small" icon="el-icon-plus" @click="handleAdd(row)">新建子区域</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" @click="$refs.crud.rowEdit(row, index)">编辑</el-button>
        <el-button type="text" size="small" icon="el-icon-view" @click="handleView(row, index)">查看</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.url"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
    <el-dialog append-to-body :close-on-click-modal="false" v-if="dialog.visible" :title="dialog.title" :visible.sync="dialog.visible" width="60%" top="5vh">
      <avue-form v-loading="dialog.loading" ref="form" class="workInfoForm" v-model="dialog.form" :option="dialog.option" @reset-change="handleReset" @submit="handleSubmit">
      </avue-form>
      <div slot="footer" class="avue-dialog__footer" v-if="dialog.title != '查 看'">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="$refs.form.submit()">保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="$refs.form.resetForm()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import importDialogComp from '@/components/dialog/import/index.vue';
import { delArea, delWarehouse, getAreaDetail, getAreaList, getWarehouseDetail, getWareHouseList, updateArea, updateWarehouse } from '@/api/warehouse/warehouseManagement';
export default {
  name: 'areaCrud',
  components: {
    importDialogComp
  },
  data() {
    return {
      importConfig: {
        title: '区域导入',
        url: '/api/mes-warehouse/area/importData',
        exportName: '区域导入模板.xlsx',
        show: false
      },
      form: {},
      query: {
        isExpand: false,
        parentId: 0
      },
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      option: {
        height: 'calc(100vh - 430px)',
        lazy: true,
        rowKey: 'id',
        rowParentKey: 'parentId',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: true,
        addBtnText: '新建区域',
        indexLabel: '序号',
        columnBtn: false,
        menuWidth: 300,
        column: [
          {
            label: '区域名称',
            prop: 'name',
            searchOrder: 1,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入区域名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '区域编码',
            prop: 'code',
            searchOrder: 2,
            search: true
          },
          {
            label: '区域等级',
            prop: 'level',
            display: false,
            formatter: (val, value, label) => {
              return 'L' + value;
            }
          },
          {
            label: '所属仓库',
            prop: 'warehouseId',
            type: 'tree',
            addDisplay: true,
            editDisplay: false,
            dicUrl: '/api/mes-warehouse/warehouse/page?current=1&size=10000&parentId=0',
            props: {
              label: 'name',
              value: 'id'
            },
            search: true,
            lazy: true,
            searchOrder: 3,
            dicData: [],
            formatter: (val, value, label) => {
              return val.warehouseName;
            },
            dicFormatter: (data) => {
              return data.data.records.map((item) => ({ ...item, leaf: !item.hasChild }));
            },
            rules: [{ required: true, message: '请选择所属仓库' }],
            treeLoad: (node, resolve) => this.loadWareHouse(node, resolve),
            change: async ({ value, column }) => {
              // if (value) {
              //   await this.getAreaByWareHouse(value);
              // }
              column.dicData.forEach((item) => {
                if (item.id === value) {
                  this.form.warehouseName = item.name;
                  this.form.warehouseCode = item.code;
                }
              });
            }
          },
          {
            label: '所属仓库',
            prop: 'warehouseName',
            disabled: true,
            hide: true,
            addDisplay: false,
            editDisplay: true
          },
          {
            label: '上级区域',
            prop: 'parentId',
            type: 'tree',
            addDisplay: false,
            editDisplay: false,
            dicData: [],
            dicFormatter: (data) => {
              return data.data.records.map((item) => ({ ...item, leaf: !item.hasChild }));
            },
            props: {
              label: 'name',
              value: 'id'
            },
            hide: true,
            lazy: true,
            treeLoad: (node, resolve) => this.loadArea(node, resolve),
            change: async ({ value, column }) => {
              column.dicData.forEach((item) => {
                if (item.id === value) {
                  this.form.parentName = item.name;
                }
              });
            }
          },
          {
            label: '上级区域',
            prop: 'parentName',
            disabled: true,
            hide: true,
            addDisplay: false,
            editDisplay: true
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            row: true,
            value: 1,
            span: 24,
            dicData: [
              { label: '禁用', value: 2 },
              { label: '启用', value: 1 }
            ],
            rules: [{ required: true, message: '请选择状态' }]
          },
          {
            label: '更新人',
            prop: 'updateByName',
            display: false
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            display: false
          },
          {
            label: '备注',
            row: true,
            span: 24,
            prop: 'remark',
            type: 'textarea'
          }
        ]
      },
      dialog: {
        visible: false,
        title: '新增子区域',
        loading: true,
        form: {},
        option: {
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 100,
          detail: false,
          column: [
            {
              label: '区域名称',
              prop: 'name',
              rules: [
                {
                  required: true,
                  message: '请输入区域名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '区域编码',
              prop: 'code'
            },
            {
              label: '所属仓库',
              prop: 'warehouseName',
              disabled: true,
              rules: [{ required: true, message: '请选择所属仓库' }]
            },
            {
              label: '上级区域',
              prop: 'parentName',
              disabled: true
            },
            {
              label: '状态',
              prop: 'status',
              type: 'switch',
              row: true,
              value: 1,
              span: 24,
              dicData: [
                { label: '禁用', value: 2 },
                { label: '启用', value: 1 }
              ],
              rules: [{ required: true, message: '请选择状态' }]
            },
            {
              label: '备注',
              row: true,
              span: 24,
              prop: 'remark',
              type: 'textarea'
            }
          ]
        }
      }
    };
  },
  async mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    const res = await getWareHouseList(1, 10000, { isExpand: false, parentId: 0 });
    let data = res.data.data && res.data.data.records;
    if (Array.isArray(data)) {
      data = data.map((item) => ({ leaf: !item.hasChild, ...item }));
    }
    const column = this.findObject(this.option.column, 'warehouseId');
    column.dicData = data || [];
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    }
  },
  methods: {
    handleAdd(row) {
      this.dialog.visible = true;
      this.dialog.loading = false;
      this.dialog.title = '新增子仓库';
      this.dialog.option.detail = false;
      this.dialog.form = structuredClone(row);
      this.dialog.form.warehouseName = row.warehouseName;
      this.dialog.form.warehouseId = row.warehouseId;
      this.dialog.form.warehouseCode = row.warehouseCode;
      this.dialog.form.parentId = row.id;
      this.dialog.form.parentName = row.name;
      this.dialog.form.name = '';
      this.dialog.form.code = '';
      this.dialog.form.id = '';
      this.dialog.form.remark = '';
    },
    async handleView(row, index) {
      this.dialog.visible = true;
      this.dialog.loading = true;
      this.dialog.title = '查 看';
      this.dialog.option.detail = true;
      const res = await getAreaDetail(row.id);
      this.dialog.loading = false;
      const form = res.data.data;
      this.dialog.form = structuredClone(form);
    },
    async handleSubmit(form, done) {
      try {
        console.log(form, 'handleSubmit ');
        await updateArea(form);
        this.dialog.visible = false;
        this.$message.success('新增成功');
        this.onLoad(this.page);
        done();
      } catch (e) {
        done();
        console.log(e);
      }
    },
    handleReset() {
      this.dialog.visible = false;
    },
    async rowSave(row, done, loading) {
      try {
        await updateArea(row);
        this.$message.success('新增成功');
        this.onLoad(this.page);

        done();
      } catch (e) {
        loading();
      }
    },
    async rowUpdate(row, index, done, loading) {
      try {
        await updateArea(row);
        this.$message.success('编辑成功');
        this.onLoad(this.page);
        done();
      } catch (e) {
        loading();
      }
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return delArea(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    async beforeOpen(done, type) {
      if (['edit'].includes(type)) {
        const res = await getAreaDetail(this.form.id);
        const form = res.data.data;
        this.form = structuredClone(form);
      }
      done();
    },
    searchReset() {
      this.query = {
        isExpand: false,
        parentId: 0
      };
      this.onLoad(this.page);
    },
    //   通过id找到对应的树节点
    searchChange(params, done) {
      let paramsLen = Object.keys(params).length;
      // 搜索
      if (paramsLen > 0) {
        params.isExpand = true;
      } else {
        // 刷新
        params.isExpand = false;
        params.parentId = 0;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const res = await getAreaList(page.currentPage, page.pageSize, Object.assign(params, this.query, {}));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map((item) => {
          return {
            ...item,
            hasChildren: item.hasChild
          };
        });
        this.loading = false;
        this.$refs.crud.refreshTable();
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    treeLoadData(tree, treeNode, resolve) {
      getAreaList(1, 10000, { parentId: tree.id }).then((res) => {
        const data = res.data.data && res.data.data.records;
        if (Array.isArray(data)) {
          data.forEach((item) => {
            if (item.hasChild) {
              item.hasChildren = true;
            }
          });
        }
        resolve(data || []);
      });
    },
    loadWareHouse(node, resolve) {
      let level = node.level;
      let data = node.data || {};
      let parentId = data.id;
      let list = [];
      let callback = () => {
        resolve(
          (list || []).map((ele) => {
            return Object.assign(ele, {
              leaf: !ele.hasChild
            });
          })
        );
      };
      if (level === 0) {
        getWareHouseList(1, 10000, { parentId: 0, isExpand: false }).then((res) => {
          list = res.data.data.records;
          callback();
        });
      } else {
        getWareHouseList(1, 10000, { parentId, isExpand: false }).then((res) => {
          list = res.data.data.records;
          callback();
        });
      }
    },
    async getAreaByWareHouse(val) {
      const column = this.findObject(this.option.column, 'parentId');
      try {
        const res = await getAreaList(1, 10000, { warehouseId: val, parentId: 0, isExpand: false });
        const data = res.data.data.records.map((item) => ({ leaf: !item.hasChild, ...item }));

        this.$nextTick(() => {
          column.dicData = data;
          this.form.parentId = '';
        });
      } catch (e) {
        console.log(e);
      }
    },
    loadArea(node, resolve) {
      if (this.form.warehouseId) {
        let level = node.level;
        let data = node.data || {};
        let parentId = data.id;
        let list = [];
        let callback = () => {
          resolve(
            (list || []).map((ele) => {
              return Object.assign(ele, {
                leaf: !ele.hasChild
              });
            })
          );
        };
        if (level === 0) {
          getAreaList(1, 10000, { warehouseId: this.form.warehouseId, parentId: 0, isExpand: false }).then((res) => {
            list = res.data.data.records;
            callback();
          });
        } else {
          getAreaList(1, 10000, { warehouseId: this.form.warehouseId, parentId, isExpand: false }).then((res) => {
            list = res.data.data.records;
            callback();
          });
        }
      }
    },
    async codeClose() {
      this.onLoad(this.page);
    },
    handleImport() {
      this.importConfig.show = true;
    }
  }
};
</script>
<style lang="scss" scoped></style>
